package com.smt.take.presenter

import android.util.Log
import com.j256.ormlite.android.AndroidDatabaseConnection
import com.j256.ormlite.dao.Dao
import com.j256.ormlite.stmt.query.In
import com.smt.take.model.beans.UserBean
import com.smt.take.model.dao.TakeOutOpenHelper
import com.smt.take.ui.activity.LoginActivity
import com.smt.take.utils.TakeOutApp
import java.lang.Exception
import java.sql.Savepoint

class LoginActivityPresenter(private val loginActivity: LoginActivity) :
    BasePresenter<UserBean>(loginActivity) {

    // 使用手机号码登陆的业务
    fun loginByPhone(phone: String) {
        val loginCall = takeOutService.getLoginByPhone(phone)
        loginCall.enqueue(callback)
    }

    // 使用手机号码登陆业务逻辑
    override fun setDataToUI(data: UserBean?) {
        if (data != null) {
            // 用户信息缓存到内存中
            TakeOutApp.sUser = data
            var connection: AndroidDatabaseConnection? = null
            var startPoint: Savepoint? = null
            try {
                // 缓存到本地数据库中SqLiteOpenHelper,要使用SQL语句
                // 第三方ORM框架(ormlite,greendao),直接操纵javaBean
                val takeOutOpenHelper = TakeOutOpenHelper(loginActivity)
                val userDao: Dao<UserBean, Int> = takeOutOpenHelper.getDao(UserBean::class.java)
                //userDao.create(data)
                //userDao.createOrUpdate(data)
                //Log.e("login", "创建新用户或者更新老用户信息")

                // AndroidDatabaseConnection(db操作,读写权限)
                connection = AndroidDatabaseConnection(takeOutOpenHelper.writableDatabase, true)
                startPoint = connection.setSavePoint("start")
                connection.isAutoCommit = false //取消自动提交
                // 区分新用户和老用户，并且统计比率
                // step1:查找以前是否有这个用户记录
                // val userInfo: UserBean = userDao.queryForId(data.id)
                val userList: List<UserBean> = userDao.queryForAll()
                var isOldUser = false
                for (i in userList.indices) {
                    if (userList[i].id == data.id) {
                        isOldUser = true
                    }
                }
                // step2:更新或者创建
                if (isOldUser) {
                    // TecentStasticSdk.userAction(-1) 伪代码，模拟用户统计
                    Log.e("login", "老用户更新信息")
                    userDao.update(data)
                } else {
                    // TecentStasticSdk.userAction(0) 伪代码，模拟用户统计
                    Log.e("login", "新用户登陆")
                    userDao.create(data)
                }
                Log.e("login", "事务正常")

                // 有数据，成功页面
                loginActivity.onHomeSuccess(data)
            } catch (e: Exception) {
                Log.e("login", "出现ormlite事务异常,${e.message}")
                connection?.let {
                    it.rollback(startPoint)
                }
                loginActivity.onHomeFailed()
            }

        } else {
            // 无数据，异常页面
            loginActivity.onHomeFailed()
        }
    }
}